from django import template
from oa_platform.models import Platform, PlatformDimension
from pirate_core import namespace_get
from django.contrib.contenttypes.models import ContentType
from pirate_consensus.models import Consensus


from customtags.decorators import block_decorator
register = template.Library()
block = block_decorator(register)

get_namespace = namespace_get('oa_platform')


@block
def pp_is_in_platform(context, nodelist, *args, **kwargs):
    context.push()
    namespace = get_namespace(context)

    object_pk = kwargs.get('object_pk', None)
    platform = kwargs.get('platform', None)

    namespace['is_in'] = object_pk in platform.planks

    output = nodelist.render(context)
    context.pop()

    return output


@block
def oa_get_platform(context, nodelist, *args, **kwargs):
    context.push()
    namespace = get_namespace(context)

    user = kwargs.get('user', None)
    ctype = kwargs.get('content_type', None)
    get_cons = kwargs.get('get_consensus', None)

    #get platform for this contenttype and user

    pl, is_new = Platform.objects.get_or_create(user=user,
                        content_type=ctype)

    if get_cons is None:
        namespace['planks'] = [ctype.get_object_for_this_type(pk=obj_id) for obj_id in pl.planks]
    else:
        namespace['planks'] = [Consensus.objects.get(object_pk=obj_id) for obj_id in pl.planks]
    namespace['platform'] = pl
    output = nodelist.render(context)
    context.pop()

    return output


@block
def oa_get_platform_dimensions(context, nodelist, *args, **kwargs):
    context.push()
    namespace = get_namespace(context)

    pl = PlatformDimension.objects.all()

    namespace['platform_dimensions'] = pl
    output = nodelist.render(context)
    context.pop()

    return output
